import React, { useState, useContext } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { AuthContext } from '../../contexts/AuthContext';

const CommentForm = ({ onSubmit, parentId = null }) => {
  const { user } = useContext(AuthContext);
  const navigate = useNavigate();
  
  const [content, setContent] = useState('');
  const [error, setError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!user) {
      navigate('/login', { state: { from: window.location.pathname } });
      return;
    }
    
    if (!content.trim()) {
      setError('评论内容不能为空');
      return;
    }
    
    setIsSubmitting(true);
    setError('');
    
    try {
      const commentData = {
        content: content.trim(),
        parentId: parentId
      };
      
      const success = await onSubmit(commentData);
      
      if (success) {
        setContent('');
      } else {
        setError('提交评论失败，请稍后重试');
      }
    } catch (err) {
      console.error('Comment submission error:', err);
      setError('评论提交时发生错误');
    } finally {
      setIsSubmitting(false);
    }
  };
  
  return (
    <div className="mb-8">
      {!user && (
        <div className="bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 p-4 rounded-md mb-4">
          请 <Link to="/login" className="text-primary-600 underline">登录</Link> 后发表评论
        </div>
      )}
      
      <form onSubmit={handleSubmit}>
        <div className="mb-3">
          <textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder={user ? "写下你的评论..." : "登录后发表评论"}
            className={`block w-full px-4 py-3 border rounded-md bg-white dark:bg-dark-800 border-gray-300 dark:border-dark-700 focus:border-primary-500 focus:ring focus:ring-primary-500/20 focus:outline-none transition ${error ? 'border-red-500' : ''}`}
            rows="4"
            disabled={!user || isSubmitting}
          ></textarea>
          {error && (
            <p className="text-red-500 text-sm mt-1">{error}</p>
          )}
        </div>
        
        <div className="flex justify-end">
          <button
            type="submit"
            className="px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 focus:outline-none focus:ring focus:ring-primary-500/50 transition disabled:opacity-50 disabled:cursor-not-allowed"
            disabled={!user || isSubmitting}
          >
            {isSubmitting ? '提交中...' : '发表评论'}
          </button>
        </div>
      </form>
    </div>
  );
};

export default CommentForm; 